package dhy.com.tomcat.oneToTwo.core;

import dhy.com.tomcat.oneToTwo.communicationEntities.Request;
import dhy.com.tomcat.oneToTwo.communicationEntities.Response;
import dhy.com.tomcat.oneToTwo.servlet.processor.ServletProcessor2;
import dhy.com.tomcat.oneToTwo.servlet.processor.StaticResourceProcessor;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.UUID;

/**
 * <p>
 *     2.0版本
 * </p>
 * @author 大忽悠
 * @create 2022/3/6 20:07
 */
public class HttpServer2 {
    static {
        System.out.println("当前工作目录为: "+System.getProperty("user.dir"));
    }


    /**
     * 关闭命令
     */
    private static final String SHUTDOWN_COMMAND="/SHUTDOWN";

    /**
     * 默认服务器端口号
     */
    private static final Integer DEFAULT_PORT=8080;

    /**
     * 关闭命令是否接收到---线程可见性
     */
    private volatile boolean shutdown=false;

    public static void main(String[] args) {
        HttpServer httpServer=new HttpServer();

        httpServer.await();
    }

    public void await() {
        ServerSocket serverSocket=null;
        try {
            //backlog设置连接队列大小,当队列中未处理的连接数超过backlog后,服务器会拒绝此次连接
            serverSocket=new ServerSocket(DEFAULT_PORT);
        } catch (IOException e) {
            e.printStackTrace();
            //通常: 0表示正常退出,1表示异常退出
            System.exit(1);
        }
        //循环等待客户端连接
        while(!shutdown)
        {
            try {
                Socket socket = serverSocket.accept();
                //TODO:后期线程池优化处理
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        doHandleAccept(socket);
                    }
                },"大忽悠线程-"+ UUID.randomUUID().toString().substring(0,5)).start();
            } catch (Exception e) {
                e.printStackTrace();
                //循环继续
                continue;
            }
        }

    }

    private void doHandleAccept(Socket socket) {
        try{
            System.out.println("当前线程: "+Thread.currentThread().getName());
            InputStream inputStream=null;
            OutputStream outputStream=null;
            inputStream=socket.getInputStream();
            outputStream=socket.getOutputStream();
            System.out.println("客户端已接入");

            System.out.println("请求对象创建中...");
            //创建请求对象并进行解析
            Request request=new Request(inputStream);
            request.parse();
            System.out.println("请求解析完毕");

            //创建响应对象并进行解析
            System.out.println("响应对象创建中");
            Response response=new Response(outputStream);
            response.setRequest(request);

            //区分资源类型
            if(request.getUri().startsWith("/servlet/"))
            {
                //servlet请求资源处理
                ServletProcessor2 processor2=new ServletProcessor2();
                processor2.process(request,response);
            }else
            {
                //静态资源请求
                StaticResourceProcessor processor=new StaticResourceProcessor();
                processor.processor(request,response);
            }
            System.out.println("响应完毕");

            //关闭当前socket连接
            socket.close();

            //检查当前URI是否是关闭命令
            shutdown=request.getUri().equals(SHUTDOWN_COMMAND);
            if(shutdown)
            {
                System.out.println("收到服务器关闭命令,即将关闭服务器.....");
            }
        }catch (Exception e)
        {
            e.printStackTrace();
        }
    }
}
